package com.wgke.bluetooth.utils;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LogUtil {

    private static final String TAG = "LogUtil";
    private static final String LOG_DIR = "MyAppLogs";
    private static final String LOG_FILE = "app_log.txt";

    private static final int MAX_LOG_LENGTH = 4000;

    public static void d(String tag, String message) {
        if (message.length() > MAX_LOG_LENGTH) {
            int chunkCount = message.length() / MAX_LOG_LENGTH;
            for (int i = 0; i <= chunkCount; i++) {
                int max = MAX_LOG_LENGTH * (i + 1);
                if (max >= message.length()) {
                    Log.d(tag, message.substring(MAX_LOG_LENGTH * i));
                } else {
                    Log.d(tag, message.substring(MAX_LOG_LENGTH * i, max));
                }
            }
        } else {
            Log.d(tag, message);
        }
    }

    public static void saveLog(String tag, byte[] data) {
        try {
            saveLog(tag, bytesToHex(data));
        }catch (Exception e){
            Log.e(TAG, "e >"+e);
        }
    }

    public static void saveLog(String tag, String message) {
        if (!isExternalStorageWritable()) {
            Log.e(TAG, "External storage not writable");
            return;
        }
        // 获取应用外部私有文件目录（不需要权限）
        File externalFilesDir = CommonUtil.getContext().getExternalFilesDir(null);

        File logDir = new File(externalFilesDir, LOG_DIR);
        if (!logDir.exists()) {
            if (!logDir.mkdirs()) {
                Log.e(TAG, "Failed to create log directory");
                return;
            }
        }

        File logFile = new File(logDir, LOG_FILE);
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
            writer.write(time + " [" + tag + "] " + message + "\n");
            writer.flush();
            writer.close();
            Log.d(TAG, "Log saved to " + message+";"+logFile.getAbsolutePath());
        } catch (IOException e) {
            Log.e(TAG, "Error writing log to file", e);
        }
    }

    private static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexBuilder = new StringBuilder();
        for (byte b : bytes) {
            // 方法1：使用 String.format（推荐）
            hexBuilder.append(String.format("%02X", b));
        }
        return hexBuilder.toString();
    }


}
